package com.lekang.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.lekang.common.utils.DateUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.domain.TaskArrangement;
import com.lekang.service.ITaskArrangementService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;

/**
 * 任务安排Controller
 * 
 * @author ruoyi
 * @date 2025-10-16
 */
@RestController
@RequestMapping("/serve/arrangement")
public class TaskArrangementController extends BaseController
{
    @Autowired
    private ITaskArrangementService taskArrangementService;

    /**
     * 查询任务安排列表
     */
    @PreAuthorize("@ss.hasPermi('serve:arrangement:list')")
    @GetMapping("/list")
    public TableDataInfo list(TaskArrangement taskArrangement)
    {
        startPage();
        // 权限控制：非超级管理员（userId != 1）只能查看自己作为护理员的任务
        Long userId = getUserId();
        System.out.println("========== 任务列表查询 ==========");
        System.out.println("当前用户ID: " + userId);
        System.out.println("查询参数中的caregiverId: " + taskArrangement.getCaregiverId());
        System.out.println("查询参数中的status: " + taskArrangement.getStatus());
        
        if (userId != 1L) {
            // 护理员只能查看自己的任务
            taskArrangement.setCaregiverId(userId);
            System.out.println("非管理员，设置caregiverId为: " + userId);
        } else {
            // 超级管理员（userId == 1）可以查看所有任务，清除可能的caregiverId过滤
            taskArrangement.setCaregiverId(null);
            System.out.println("管理员，清除caregiverId过滤");
        }
        
        List<TaskArrangement> list = taskArrangementService.selectTaskArrangementList(taskArrangement);
        System.out.println("查询结果数量: " + list.size());
        System.out.println("==================================");
        return getDataTable(list);
    }

    /**
     * 导出任务安排列表
     */
    @PreAuthorize("@ss.hasPermi('serve:arrangement:export')")
    @Log(title = "任务安排", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TaskArrangement taskArrangement)
    {
        List<TaskArrangement> list = taskArrangementService.selectTaskArrangementList(taskArrangement);
        ExcelUtil<TaskArrangement> util = new ExcelUtil<TaskArrangement>(TaskArrangement.class);
        util.exportExcel(response, list, "任务安排数据");
    }

    /**
     * 获取任务安排详细信息
     */
    @PreAuthorize("@ss.hasPermi('serve:arrangement:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(taskArrangementService.selectTaskArrangementById(id));
    }

    /**
     * 新增任务安排
     */
    @PreAuthorize("@ss.hasPermi('serve:arrangement:add')")
    @Log(title = "任务安排", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TaskArrangement taskArrangement)
    {
        return toAjax(taskArrangementService.insertTaskArrangement(taskArrangement));
    }

    /**
     * 修改任务安排
     */
    @PreAuthorize("@ss.hasPermi('serve:arrangement:edit')")
    @Log(title = "任务安排", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TaskArrangement taskArrangement)
    {
        return toAjax(taskArrangementService.updateTaskArrangement(taskArrangement));
    }

    /**
     * 删除任务安排
     */
    @PreAuthorize("@ss.hasPermi('serve:arrangement:remove')")
    @Log(title = "任务安排", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(taskArrangementService.deleteTaskArrangementByIds(ids));
    }



    /**
     * 取消任务
     */
    @PreAuthorize("@ss.hasPermi('serve:arrangement:cancel')")
    @Log(title = "任务安排", businessType = BusinessType.UPDATE)
    @PutMapping("/cancel/{taskId}")
    public AjaxResult cancelTask(@PathVariable Long taskId, @RequestBody String cancelReason) {
        return toAjax(taskArrangementService.cancelTask(taskId, cancelReason));
    }

    /**
     * 执行任务
     */
    @PreAuthorize("@ss.hasPermi('serve:arrangement:execute')")
    @Log(title = "任务安排", businessType = BusinessType.UPDATE)
    @PutMapping("/execute/{taskId}")
    public AjaxResult executeTask(
            @PathVariable Long taskId,
            @RequestBody Map<String, Object> params) {
        Date executionTime = DateUtils.parseDate(params.get("executionTime").toString());
        String executionImage = (String) params.get("executionImage");
        String executionRecord = (String) params.get("executionRecord");
        return toAjax(taskArrangementService.executeTask(taskId, executionTime, executionImage, executionRecord));
    }

    /**
     * 改期任务
     */
    @PreAuthorize("@ss.hasPermi('serve:arrangement:reschedule')")
    @Log(title = "任务安排", businessType = BusinessType.UPDATE)
    @PutMapping("/reschedule/{taskId}")
    public AjaxResult rescheduleTask(
            @PathVariable Long taskId,
            @RequestBody Map<String, Object> params) {
        Date newExpectedTime = DateUtils.parseDate(params.get("newExpectedTime").toString());
        Date rescheduleTime = new Date(); // 改期时间为当前操作时间
        return toAjax(taskArrangementService.rescheduleTask(taskId, newExpectedTime, rescheduleTime));
    }

    /**
     * 根据关联单据号查询任务安排
     */
//    @PreAuthorize("@ss.hasPermi('serve:arrangement:list')")
    @GetMapping("/relatedOrder/{relatedOrderNo}")
    public AjaxResult getByRelatedOrderNo(@PathVariable("relatedOrderNo") String relatedOrderNo)
    {
        return success(taskArrangementService.selectTaskArrangementByRelatedOrderNo(relatedOrderNo));
    }

}
